<?php
/**
 * 用户中心SDK
 * 
 * @author ShuangYa
 * @package EUser
 * @category SDK
 * @copyright Copyright (c) 2015-2016 ShuangYa
 * @link http://lab.sylingd.com/go.php?name=euser&type=license
 */

/***********************
 *
 * SDK需求：
 * php 5.4+
 * swoole/curl组件
 *
 ***********************
 *
 * 基本说明：
 * 1.将配置粘贴到下方
 * 2.完成
 *
 ***********************/

final class EUser {
	protected static $conn;
	const VERSION = '1.2';
	//将配置粘贴到此处
	public static $config = [
		'connect' => 'swoole',
		'client_id' => '570e5d61e3edf4c71a4758a8',
		'client_secret' => '1d06f6f2b8f2711d15c85ee1f51ff997',
		'cookie_prefix' => '',
		'server' => [
			'url' => 'http://eu.sy/',
			'addr' => '127.0.0.1',
			'port' => 9501
		]
	];
	//初始化
	protected static function init() {
		if (!is_object(self::$conn)) {
			$conn_file = 'EUser_' . self::$config['connect'];
			$conn_class = __NAMESPACE__ . '\\' . $conn_file;
			if (!class_exists($conn_class)) {
				require(__DIR__ . '/' . $conn_file . '.php');
			}
			self::$conn = new $conn_class(self::$config);
		}
	}
	/**
	 * 获取登出（注销）URL
	 * 注销时，首先由App做相关清理工作，然后跳转到此URL
	 * @access public
	 * @return string
	 */
	public static function getLoginoutUrl($redirect = NULL) {
		$param = ['_t' => microtime(TRUE)];
		if (NULL !== $redirect) {
			$param['redirect'] = $redirect;
		}
		return self::$config['server']['url'] . 'user/loginout.html?' . http_build_query($param);
	}
	/**
	 * OAuth：获取Authorize地址，用于跳转到EUser进行登陆
	 * @access public
	 * @param string $redirect_uri 回调URL
	 * @param string $state 可选，回调时将原样回传，用于防止CROS攻击
	 * @param string $display 可选，模板类型
	 * @return string
	 */
	public static function getAuthorizeUrl($redirect_uri, $state = '', $display = 'default') {
		return self::$config['server']['url'] . 'oauth/authorize?' . http_build_query([
			'client_id' => self::$config['client_id'],
			'response_type' => 'code',
			'redirect_uri' => $redirect_uri,
			'state' => $state,
			'display' => $display
		]);
	}
	/**
	 * OAuth：使用AuthorizeCode换取AccessToken
	 * @access public
	 * @param string $redirect_uri 获取AuthorizeCode时传递的redirect_uri
	 * @param string $code AuthorizeCode
	 * @return array
	 */
	public static function getAccessToken($redirect_uri, $code) {
		self::init();
		$result = self::get('oauth/token', [
			'grant_type' => 'authorize_code',
			'client_secret' => self::$config['client_secret'],
			'redirect_uri' => $redirect_uri,
			'code' => $code
		]);
		return $result;
	}
	/**
	 * 校验Cookie是否有效
	 * 当应用与EUser根域名相同时（例如应用域名为app.example.com，EUser域名为member.example.com）推荐使用此方法完成认证
	 * 认证通过时，将返回Token信息
	 * 认证失败时，将返回FALSE
	 * @access public
	 * @return array
	 */
	public static function verifyCookie($cookie = NULL) {
		self::init();
		if ($cookie === NULL) {
			if (!isset($_COOKIE[self::$config['cookie_prefix'] . 'token']) || !isset($_COOKIE[self::$config['cookie_prefix'] . 'tverify'])) {
				return FALSE;
			}
			$token = $_COOKIE[self::$config['cookie_prefix'] . 'token'];
			$tverify = $_COOKIE[self::$config['cookie_prefix'] . 'tverify'];
		} else {
			if (!isset($cookie[self::$config['cookie_prefix'] . 'token']) || !isset($cookie[self::$config['cookie_prefix'] . 'tverify'])) {
				return FALSE;
			}
			$token = $cookie[self::$config['cookie_prefix'] . 'token'];
			$tverify = $cookie[self::$config['cookie_prefix'] . 'tverify'];
			
		}
		$result = self::get('user/getToken', ['token' => $token, 'tverify' => $tverify]);
		return isset($result['token']) ? $result['token'] : FALSE;
	}
	/**
	 * 校验Cookie是否存在
	 * @access public
	 * @return array
	 */
	public static function issetCookie($cookie = NULL) {
		self::init();
		if ($cookie === NULL) {
			return isset($_COOKIE[self::$config['cookie_prefix'] . 'token']);
		} else {
			return isset($cookie[self::$config['cookie_prefix'] . 'token']);
		}
	}
	/**
	 * 获取token信息
	 * 认证通过时，将返回Token信息
	 * 认证失败时，将返回FALSE
	 * @access public
	 * @return array
	 */
	public static function getToken($token) {
		self::init();
		$result = self::get('user/getToken', ['token' => $token]);
		return isset($result['token']) ? $result['token'] : FALSE;
	}
	/**
	 * 获取用户信息
	 * @access public
	 * @param array $filter 筛选条件，仅允许用户名或用户ID，格式：['name' => '用户名']或['uid' => '用户ID']
	 * @return array
	 */
	public static function getUser($filter) {
		self::init();
		if (!in_array(key($filter), ['uid', 'name'], TRUE)) {
			return NULL;
		}
		$result = self::get('user/info', $filter);
		return $result;
	}
	/**
	 * 添加用户
	 * @access public
	 * @param array $userinfo
	 * @param string $userinfo['name'] 用户名
	 * @param string $userinfo['password'] 密码
	 * @return string
	 */
	public static function addUser($userinfo) {
		self::init();
		if (!isset($userinfo['name'])) {
			return FALSE;
		}
		if (!isset($userinfo['password'])) {
			return FALSE;
		}
		$result = self::get('user/add', ['user' => $userinfo]);
		return $result['id'];
	}
	/**
	 * 获取App信息
	 * @access public
	 * @param string $id 应用ID
	 * @return array
	 */
	public static function getApp($id) {
		self::init();
		$result = self::get('app/get', ['id' => $id]);
		return $result;
	}
	/**
	 * 按Key加密
	 * @access public
	 * @param string $key
	 * @param string $data
	 * @return string
	 */
	public static function makeSign($key, $data) {
		return hash_hmac('md5', $data, $key);
	}
	/**
	 * 调用API
	 * @access protected
	 * @param string $route 路由名称
	 * @param array $data 数据
	 * @return array
	 */
	protected static function get($route, $data = []) {
		$data['client_id'] = self::$config['client_id'];
		ksort($data);
		$sign = self::makeSign(self::$config['client_secret'], json_encode($data));
		return self::$conn->get($route, $data, $sign);
	}
}